<template>
  <div>
    <x-header :left-options="{showBack: false}">人头计数</x-header>

    <group title="" title-color="blue">
      <x-input title="PC端IP地址" v-model="ip" placeholder="请输入PC端IP地址" :show-clear="true"></x-input>
    </group>

    <box gap="10px 10px">
      <x-button :gradients="gradients" @click.native="onClickConnect">{{connected ? '连接成功' : '连接PC'}}</x-button>
    </box>

    <div v-for="camera in cameras" :key="camera.index">
      <card :header="{title: '摄像头 ' + camera.index}" class="card">
        <div slot="content" class="card-flex card-content">

          <!--
          <div>
            <span class="span-count">{{camera.count}}</span>
            <br/>
            计数
          </div>
          -->

          <div>
            <span :class="statusClass(camera.status)">{{statusText(camera.status)}}</span>
            <br/>
            状态
          </div>
          <div>
            <span class="span-exception">{{exceptionText(camera.exception)}}</span>
            <br/>
            是否异常移动?
          </div>
        </div>
      </card>
    </div>

    <!-- <box gap="10px 10px">
    <flexbox :gutter="8">
      <flexbox-item v-for="camera in cameras" :key="camera.index">
        <x-button :gradients="cameraGradients(camera)" @click.native="onClickCamera(camera)">摄像头 {{camera.index}}</x-button>
      </flexbox-item>
    </flexbox>
    </box>

    <div class="vux-result">
      <h3>统计结果: {{count}}</h3>
      <div id="count-image" v-if="cameraConnected">
      </div>
      <img class="logo" src="../assets/vux_logo.png" v-if="!cameraConnected">
    </div> -->

  </div>
</template>

<script>
import { Group, Cell, XInput, XButton, Box, Flexbox, FlexboxItem, XHeader, Divider, Card } from 'vux'
import Rest from '@/service/rest'
import HttpApi from '@/service/httpApi'

const STATUS_EMPTY = 1
const STATUS_FULL = 2
const STATUS_CROWD = 3
const STATUS_VERYCROWD = 4

export default {
  components: {
    Group,
    Cell,
    XButton,
    Box,
    Flexbox,
    FlexboxItem,
    XHeader,
    Divider,
    Card,
    XInput
  },
  data () {
    return {
      ip: '192.168.3.53',
      connected: false,
      cameras: [],
      cameraCount: 1,
      cameraConnected: false,
      count: 0,
      websocket: null
    }
  },
  computed: {
    gradients () {
      return this.connected ? ['#1AAD19', '#1AAD19'] : ['#0E88EB', '#0E88EB']
    }
  },
  created () {
  },
  methods: {
    exceptionText (exception) {
      return exception ? '人员异常移动' : '无'
    },
    statusText (status) {
      if (status === STATUS_EMPTY) {
        return '空'
      } else if (status === STATUS_FULL) {
        return '满'
      } else if (status === STATUS_CROWD) {
        return '拥挤'
      } else if (status === STATUS_VERYCROWD) {
        return '很拥挤'
      }
      return '很拥挤'
    },
    statusClass (status) {
      if (status === STATUS_EMPTY) {
        return 'status-empty'
      } else if (status === STATUS_FULL) {
        return 'status-full'
      } else if (status === STATUS_CROWD) {
        return 'status-crowd'
      }
      return 'status-verycrowd'
    },
    makeCamera (index) {
      return {index: index, status: STATUS_EMPTY, count: 0, exception: false, name: '' + index}
    },
    onClickConnect () {
      if (this.connected) {
        this.disconnect()
      } else {
        if (!this.ip) {
          this.$vux.toast.show({
            type: 'warn',
            text: '请指定PC端IP地址'
          })
          return
        }

        this.connect()
      }
    },
    getHttpUrl () {
      return `http://${this.ip}:18800/`
    },
    getWebSocketUrl (ip, port) {
      return `ws://${ip}:${port}/api/ws/`
    },
    connectCamera () {
      let port = 18800
      let url = this.getWebSocketUrl(this.ip, port)
      let websocket = new WebSocket(url)
      websocket.onmessage = this.onMessage
      websocket.onopen = this.onOpen
      websocket.onclose = this.onClose
      this.websocket = websocket
    },
    disconnectCamera () {
      this.cameraConnected = false
      this.websocket.onclose = function () {} // disable onclose handler first
      this.websocket.close()
      this.websocket = null
    },
    connect () {
      Rest.setApiUrl(this.getHttpUrl())
      HttpApi.getCamera().then((data) => {
        console.log(data)

        let cameras = []
        for (let i = 0; i < data.count; i++) {
          cameras.push(this.makeCamera(i))
        }
        this.cameras = cameras

        this.connected = true
        this.cameraCount = data.count
        this.$vux.toast.show({
          type: 'info',
          text: `摄像头数量: ${data.count}`
        })

        this.connectCamera()
      }).catch(error => {
        console.log(error)
        this.$vux.toast.show({
          type: 'warn',
          text: '连接失败, 确保IP正确, PC端打开'
        })
      })
    },
    disconnect () {
      this.connected = false

      if (this.cameraConnected) {
        this.disconnectCamera()
      }
    },
    onMessage (event) {
      // console.log(event)
      if (typeof (event.data) === 'string') {
        let msg = JSON.parse(event.data)
        this.onTextMessage(msg)
      } else {
        var reader = new FileReader()
        reader.onload = this.onLoad
        reader.readAsDataURL(event.data)
      }
    },
    onOpen (event) {
      this.cameraConnected = true
    },
    onClose (event) {
      this.cameraConnected = false
    },
    onLoad (event) {
      if (event.target.readyState === FileReader.DONE) {
        let url = event.target.result
        let img = document.getElementById('count-image')
        if (img) {
          img.innerHTML = '<img class="count-image" src = ' + url + ' />'
        }
      }
    },
    onTextMessage (msg) {
      // console.log(msg)
      if (msg.count) {
        let camera = this.cameras[msg.index]
        camera.count = msg.count
        camera.status = msg.status
        camera.exception = msg.exception
      }
    },
    onClickCamera (camera) {
      if (this.cameraConnected) {
        this.disconnectCamera()
      } else {
        this.connectCamera(camera.index)
      }
    }
  }
}
</script>

<style>

.vux-result {
  text-align: center;
}

#count-image {
  margin-top: 8px;
}

.count-image {
  width: 100%;
}

.logo {
  margin-top: 8px;
  width: 100%;
}

.card {
  margin-bottom: 8px;
}

.card-flex {
  display: flex;
}

.card-content {
  padding: 4px 0;
}

.card-flex > div {
  flex: 1;
  text-align: center;
  font-size: 12px;
}

.span-count {
  color: blue;
  font-size: 2em;
}

.status-empty {
  color: blue;
  font-size: 2em;
}

.status-full {
  color: yellow;
  font-size: 2em;
}

.status-crowd {
  color: orange;
  font-size: 2em;
}

.status-verycrowd {
  color: red;
  font-size: 2em;
}

.span-exception {
  color: red;
  font-size: 2em;
}

</style>
